package com.landi.carkey;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.landi.carkey.core.BaseListActivity;
import com.landi.carkey.greendao.KeyModel;
import com.landi.carkey.greendao.KeyModelDao;
import com.landi.carkey.interfaces.IDialogCheckPassWord;
import com.landi.carkey.interfaces.IDialogTimeoutListener;
import com.landi.carkey.manager.GreenDaoManager;
import com.landi.carkey.manager.LocationManger;
import com.landi.carkey.manager.UpDataVersionManager;
import com.landi.carkey.pull.BaseViewHolder;
import com.landi.carkey.ui.WebViewActivity;
import com.landi.carkey.util.DateUtil;
import com.landi.carkey.util.DialogFactory;
import com.landi.carkey.util.SharePreferenceUtils;
import com.landi.carkey.util.ToastUtil;

import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseListActivity<KeyModel> {

    @BindView(R.id.et_number)
    EditText mNumberEt;
    @BindView(R.id.et_password)
    EditText mPasswordEt;
    /**
     * UserText表对象
     */
    private KeyModelDao keyModelDao;

    //重写父类布局
    @Override
    protected void setUpContentView() {
        setContentView(R.layout.activity_main, R.string.mobile_name, MODE_HOME);
    }

    @Override
    protected void setUpView() {
        super.setUpView();

        setToolbarRight("同行", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                startActivity(intent);
            }
        });

        mNumberEt = (EditText) findViewById(R.id.et_number);
        mPasswordEt = (EditText) findViewById(R.id.et_password);
        keyModelDao = GreenDaoManager.getInstance().getSession().getKeyModelDao();
    }

    @Override
    protected void setUpData() {
        super.setUpData();
        recycler.enablePullToRefresh(false);
        recycler.setRefreshing();

        UpDataVersionManager.getInstance(this).checkVersion();

        LocationManger.getInstance(this).initLocation();
        LocationManger.getInstance(this).locationStart();
    }

    /**
     * Button 点击的监听事件
     *
     * @param view
     */
    public void onMyButtonClick(View view) {
        switch (view.getId()) {
            case R.id.buttonAdd:
                addNote();
                break;
            case R.id.buttonQuery:
                search(mNumberEt.getText().toString());
                break;
            case R.id.buttonClear:
                DialogFactory.showInputPassWordDialog(this, "清除本地所有数据", "确定", new IDialogCheckPassWord() {
                    @Override
                    public void onDialogCheckStr(String tip) {

                        if (TextUtils.isEmpty(tip)) {
                            ToastUtil.toast("请输入密码");
                            return;
                        }

                        if (tip.equals("landi")) {
                            clearAll();
                            recycler.setRefreshing();
                            DialogFactory.dismissAlert(MainActivity.this);
                        } else {
                            ToastUtil.toast("密码错误");
                        }

                    }
                }, "取消", null);
                break;
            case R.id.buttonUpdata:
                updataFromServer();
                break;
            default:
                ToastUtil.toast("点击出错");
                break;
        }
    }

    /**
     * 拉去服务端数据到本地数据库
     */
    private void updataFromServer() {

        DialogFactory.showLoadingDialog(this, "", "");

        AVQuery<AVObject> query = new AVQuery<>(GreenDaoManager.TABLE_NAME);
        query.limit(1000);
        query.whereContains("city", SharePreferenceUtils.getPrefString(this, "city", ""));
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> todos, AVException e) {

                if (e == null) {

                    if (todos == null) {
                        DialogFactory.dismissAlert(MainActivity.this);
                        ToastUtil.toast("更新数据失败！");
                        return;
                    }

                    if (todos.size() == 0) {
                        DialogFactory.dismissAlert(MainActivity.this);
                      ToastUtil.toast("无数据！");
                        return;
                    }

                    GreenDaoManager.getInstance().upDataLocalDataBase(MainActivity.this,todos, new IDialogTimeoutListener() {
                        @Override
                        public void onDialogTimeout(String tip) {
                            DialogFactory.dismissAlert(MainActivity.this);
                            recycler.setRefreshing();
                        }
                    });
                } else {
                    DialogFactory.dismissAlert(MainActivity.this);
                    ToastUtil.toast("更新数据出错！");
                }
            }
        });
    }


    /**
     * add
     */
    private void addNote() {
        final String number = mNumberEt.getText().toString();
        final String password = mPasswordEt.getText().toString();

        if (TextUtils.isEmpty(number) || TextUtils.isEmpty(password)) {
            ToastUtil.toast("请输入车牌号或密码");
            return;
        }
        //如果本地无此数据，则再插入
        KeyModel model = keyModelDao.queryBuilder().where(KeyModelDao.Properties.Number.eq(number),
                KeyModelDao.Properties.PassWord.eq(password)).build().unique();
        if (model == null) {

            DialogFactory.showMessage(this, "提示", "确定要添加数据？\n" + number + "\n" + password, "确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 插入操作，简单到只要你创建一个 Java 对象
                    String contributor  =  AVUser.getCurrentUser().getUsername();
                    String city = SharePreferenceUtils.getPrefString(MainActivity.this,"city","");
                    final long id = keyModelDao.insert(new KeyModel(null, number, password,
                            DateUtil.getCurrentTime(), null,contributor, null, city));
                    ToastUtil.toast("插入本地数据成功，ID= " + id);

                    //刷新列表数据
                    recycler.setRefreshing();
                    DialogFactory.dismissAlert(MainActivity.this);

                    //上送数据到服务器
                    final AVObject todoFolder = new AVObject(GreenDaoManager.TABLE_NAME);// 构建对象
                    todoFolder.put(GreenDaoManager.FILED_NUMBER, number);
                    todoFolder.put(GreenDaoManager.FILED_PASSWORD, password);
                    todoFolder.put(GreenDaoManager.FILED_CONTRIBUTOR, contributor);
                    Log.d("","***上送数据时地址****"+city+"   "+city.equals("上海市"));
                    todoFolder.put(GreenDaoManager.FILED_CITY,city);
                    todoFolder.saveEventually(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e == null) {
                                KeyModel model = keyModelDao.queryBuilder().where(KeyModelDao.Properties.Id.eq(id)).build().unique();
                                if (model != null) {//更新云ID
                                    model.setCloudId(todoFolder.getObjectId());
                                    keyModelDao.update(model);
                                    ToastUtil.toast("上送云服务数据成功");
                                    clearEditInput();
                                }
                            } else {
                                ToastUtil.toast("上送云服务数据失败");
                            }
                        }
                    });
                }
            }, "取消", null);
        } else {
            ToastUtil.toast("本地已有此数据,请勿重复添加");
        }
    }

    /**
     * @param number 车牌号
     */
    private void search(String number) {

        if (TextUtils.isEmpty(number)) {
            ToastUtil.toast("请输入要查询的车牌号");
            recycler.setRefreshing();
        } else {

            mDataList = keyModelDao.queryBuilder()
                    .where(KeyModelDao.Properties.Number.like("%" + number + "%")).orderDesc(KeyModelDao.Properties.Id).build().list();
            Log.d("", "******search******" + mDataList.size());
            adapter.notifyDataSetChanged();
        }
    }

    private void clearAll() {
        keyModelDao.deleteAll();
        clearEditInput();
    }

    @Override
    protected BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_number_key, parent, false);
        return new KeyViewHolder(view);
    }

    @Override
    public void onRefresh(int action) {
        Log.d("", "******onRefresh******");
        //此处先做读本地数据库处理
        if (mDataList != null) {
            mDataList.clear();
        }

        if (mDataList == null || mDataList.size() == 0) {
            mDataList = keyModelDao.queryBuilder().orderDesc(KeyModelDao.Properties.Id).list();
            Log.d("", "******onRefresh******" + mDataList.size());
        }

        if (mDataList == null) {
            recycler.onRefreshCompleted();
            return;
        }
        adapter.notifyDataSetChanged();
        recycler.onRefreshCompleted();
    }

    private class KeyViewHolder extends BaseViewHolder {
        private TextView mIdTv;
        private TextView mContributorTv;
        private TextView mNumberTv;
        private TextView mPassWordTv;
        private TextView mTimeTv;

        public KeyViewHolder(View view) {
            super(view);
            mIdTv = (TextView) view.findViewById(R.id.item_id_tv);
            mContributorTv = (TextView)view.findViewById(R.id.item_contributor_tv);
            mNumberTv = (TextView) view.findViewById(R.id.item_number_tv);
            mPassWordTv = (TextView) view.findViewById(R.id.item_password_tv);
            mTimeTv = (TextView) view.findViewById(R.id.item_time);
        }

        @Override
        public void onBindViewHolder(int position) {
            mIdTv.setText(mDataList.get(position).getId() + "");
            if (TextUtils.isEmpty(mDataList.get(position).getContributor())){
                mContributorTv.setText("雷锋");
            }else{
                mContributorTv.setText(mDataList.get(position).getContributor());
            }
            mNumberTv.setText(mDataList.get(position).getNumber());
            mPassWordTv.setText(mDataList.get(position).getPassWord());
            mTimeTv.setText(mDataList.get(position).getUpdateTime().substring(0,10));
        }

        @Override
        public void onItemClick(View view, final int position) {

            //根据id删除

            DialogFactory.showMessage(MainActivity.this, "警告", "确定要删除该数据？\n" +
                    mDataList.get(position).getNumber() + "\n" + mDataList.get(position).getPassWord(), "确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtil.toast("本地记录删除, 车牌号：" + mDataList.get(position).getNumber());
                    keyModelDao.delete(mDataList.get(position));
                    mDataList.remove(position);
                    adapter.notifyDataSetChanged();
                    DialogFactory.dismissAlert(MainActivity.this);
                }
            }, "取消", null);

        }
    }

    private void clearEditInput() {
        mPasswordEt.setText("");
        mNumberEt.setText("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationManger.getInstance(this).locationStop();
    }
}
